package luren.king.wechatlite.activity;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Looper;
import android.os.Process;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.text.MessageFormat;

import luren.king.wechatlite.R;
import luren.king.wechatlite.config.Config;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class SettingActivity extends AppCompatActivity {
    private static final String TAG = "彔忈-King";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_setting);

//        修改密码、修改昵称、退出登录
        LinearLayout change_password = findViewById(R.id.change_password);
        LinearLayout change_nickname = findViewById(R.id.change_informations);
        LinearLayout logout = findViewById(R.id.log_out);

        change_password.setOnClickListener(v -> {

            View view = getLayoutInflater().inflate(R.layout.change_password, null);
            AlertDialog.Builder newBuilder = new AlertDialog.Builder(this)
                    .setCancelable(false)
                    .setView(view);
            AlertDialog alert = newBuilder.create();
            alert.show();

            EditText old = view.findViewById(R.id.editTextOldPassword);
            EditText New = view.findViewById(R.id.editTextNewPassword);
            EditText ConfirmPsw = view.findViewById(R.id.editTextConfirmPassword);

            Button Confirm = view.findViewById(R.id.buttonConfirm);
            Confirm.setOnClickListener(v1 -> {
//                Toast.makeText(this, "成功或者失败更改密码", Toast.LENGTH_LONG).show();
                alert.dismiss();

                String newpsd = New.getText().toString();
                String cnewpsd = ConfirmPsw.getText().toString();
                if (!newpsd.equals(cnewpsd)){
                    Toast.makeText(SettingActivity.this, "两次密码不一致", Toast.LENGTH_LONG).show();
                    return;
                }
                AlertDialog.Builder builder = new AlertDialog.Builder(SettingActivity.this);

                // 加载自定义的布局
                LayoutInflater inflater = getLayoutInflater();
                View dialogView = inflater.inflate(R.layout.custom_loading_dialog, null);

                // 设置自定义背景
                dialogView.setBackgroundResource(R.drawable.dialog_background);

                // 设置Dialog的视图
                builder.setView(dialogView);

                // 创建并显示AlertDialog
                AlertDialog alertDialog = builder.create();
                alertDialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent); // 设置窗口背景透明
                alertDialog.setCancelable(false); // 禁用取消操作（例如点击外部取消）

                alertDialog.show();

                new Thread() {
                    @Override
                    public void run() {
                        Looper.prepare();
                        try {
                            OkHttpClient client = new OkHttpClient().newBuilder()
                                    .build();
                            MediaType mediaType = MediaType.Companion.parse("application/json;charset=utf-8");
                            RequestBody body = RequestBody.Companion.create("{\n" +
                                    "    \"password\":\""+old.getText()+"\",\n" +
                                    "    \"newPassword\":\""+newpsd+"\"\n" +
                                    "}", mediaType);
                            Request request = new Request.Builder()
                                    .url(Config.DEFAULT_URL + "/userInfo/updateUserPwd")
                                    .method("PUT", body)
                                    .addHeader("token", Config.JWT_TOKEN)
                                    .addHeader("User-Agent", "Apifox/1.0.0 (https://apifox.com)")
                                    .addHeader("Content-Type", "application/json")
                                    .build();
                            Response response = client.newCall(request).execute();
                            String rsg = response.body().string();
                            JSONObject json = new JSONObject(rsg);
                            alertDialog.dismiss();
                            Toast.makeText(SettingActivity.this, json.getString("msg"), Toast.LENGTH_LONG).show();
                        } catch (Exception e) {
                            alertDialog.dismiss();
                            Toast.makeText(SettingActivity.this, e.getMessage(), Toast.LENGTH_LONG).show();
                        }
                        Looper.loop();
                    }
                }.start();
            });
            Button Cancel = view.findViewById(R.id.buttonCancel);
            Cancel.setOnClickListener(v1 -> {
                alert.dismiss();
            });

        });

        change_nickname.setOnClickListener(v -> {
            AlertDialog.Builder builder = new AlertDialog.Builder(this);

            // 加载自定义的布局
            LayoutInflater inflater = getLayoutInflater();
            View dialogView = inflater.inflate(R.layout.custom_loading_dialog, null);

            // 设置自定义背景
            dialogView.setBackgroundResource(R.drawable.dialog_background);

            // 设置Dialog的视图
            builder.setView(dialogView);

            // 创建并显示AlertDialog
            AlertDialog alertDialog = builder.create();
            alertDialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent); // 设置窗口背景透明
            alertDialog.setCancelable(false); // 禁用取消操作（例如点击外部取消）

            alertDialog.show();

            new Thread() {
                @Override
                public void run() {
                    Looper.prepare();
                    try {
                        OkHttpClient client = new OkHttpClient().newBuilder()
                                .build();
                        Request request = new Request.Builder()
                                .url(Config.DEFAULT_URL + "/userInfo/getUserInfo")
                                .addHeader("token", Config.JWT_TOKEN)
                                .addHeader("User-Agent", "Apifox/1.0.0 (https://apifox.com)")
                                .build();
                        Response response = client.newCall(request).execute();
                        String rsg = response.body().string();
                        JSONObject json = new JSONObject(rsg);
                        runOnUiThread(() -> {
                            try {
                                if (json.getInt("code") == 200) {
                                    alertDialog.dismiss();
                                    JSONObject data = json.getJSONObject("data");
                                    View view = getLayoutInflater().inflate(R.layout.change_informaiton, null);
                                    AlertDialog.Builder newbuilder = new AlertDialog.Builder(SettingActivity.this)
                                            .setView(view);
                                    AlertDialog dialog = newbuilder.create();
                                    dialog.show();
                                    EditText nickname = view.findViewById(R.id.editTextNickname);
                                    EditText personal = view.findViewById(R.id.editTextSignature);
                                    EditText area = view.findViewById(R.id.editTextRegion);
                                    @SuppressLint({"MissingInflatedId", "LocalSuppress"})
                                    Button confirm = view.findViewById(R.id.confirm_change);
                                    RadioGroup group = view.findViewById(R.id.radioGroupGender);
                                    RadioButton man = view.findViewById(R.id.radioButtonMale);
                                    RadioButton women = view.findViewById(R.id.radioButtonFemale);
                                    nickname.setText(data.getString("nick_name"));
                                    personal.setText(data.getString("personal_signature"));
                                    area.setText(data.getString("area_name"));
                                    int sexx = 2;
                                    try {
                                        sexx = data.getInt("sex");
                                    } catch (JSONException ignored) {
                                    }
                                    if (sexx == 1) {
                                        group.check(R.id.radioButtonMale);
                                    } else if (sexx == 0){
                                        group.check(R.id.radioButtonFemale);
                                    }
                                    confirm.setOnClickListener(v1 -> {
                                        int selectID = group.getCheckedRadioButtonId();
                                        int sex;
                                        if (selectID == man.getId()){
                                            sex = 1;
                                        }else {
                                            sex = 0;
                                        }
                                        try {
                                            JSONObject information = new JSONObject();
                                            information.put("nick_name", nickname.getText().toString());
                                            information.put("sex", sex);
                                            information.put("personal_signature", personal.getText().toString());
                                            information.put("area_name", area.getText().toString());
                                            new Thread(){
                                                @Override
                                                public void run() {
                                                    Looper.prepare();
                                                    try {
                                                        MediaType mediaType = MediaType.Companion.parse("application/json");
                                                        RequestBody body = RequestBody.Companion.create(information.toString(), mediaType);
                                                        Request change = new Request.Builder()
                                                                .url(Config.DEFAULT_URL+"/userInfo/updateUserInfo")
                                                                .method("PUT", body)
                                                                .addHeader("token", Config.JWT_TOKEN)
                                                                .build();
                                                        Response rsp = client.newCall(change).execute();
                                                        String rsp_s = rsp.body().string();
                                                        Toast.makeText(SettingActivity.this, new JSONObject(rsp_s).getString("msg"), Toast.LENGTH_LONG).show();
                                                        dialog.dismiss();
                                                    } catch (Exception e) {
//                                                        throw new RuntimeException(e);
                                                        dialog.dismiss();
                                                        Toast.makeText(SettingActivity.this, e.getMessage(), Toast.LENGTH_LONG).show();
                                                    }
                                                    Looper.loop();
                                                }
                                            }.start();
                                        } catch (Exception e) {
                                            Log.d(TAG, "run: " + e);
//                                            Toast.makeText(SettingActivity.this, e.getMessage(), Toast.LENGTH_LONG).show();
                                        }

                                    });
                                } else {
                                    alertDialog.dismiss();
                                    Toast.makeText(SettingActivity.this, json.getString("msg"), Toast.LENGTH_LONG).show();
                                }
                            } catch (JSONException e) {
                                Toast.makeText(SettingActivity.this, e.getMessage(), Toast.LENGTH_LONG).show();
                                Log.d(TAG, "run: " + e);
                            }

                        });

                    } catch (JSONException | IOException e) {
                        alertDialog.dismiss();
                        String errorMessage = e.getClass().getName() + ": " + e.getMessage();
                        StringBuilder sbException = new StringBuilder();
                        sbException.append(errorMessage).append("\n");
                        for (StackTraceElement ele : e.getStackTrace()) {
                            sbException.append(MessageFormat.format("\tat {0}.{1}({2}:{3})\n",
                                    ele.getClassName(), ele.getMethodName(), ele.getFileName(), ele.getLineNumber()));
                        }
                        android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(SettingActivity.this);
                        builder.setTitle("操作失败");
                        builder.setMessage(sbException.toString());
                        builder.setPositiveButton("确定", (dialog, which) -> {
                            dialog.dismiss();
                        });
                        builder.show();
                        Log.d(TAG, "run: " + sbException.toString());
                    }
                    Looper.loop();
                }
            }.start();
        });

        logout.setOnClickListener(v -> {
            AlertDialog.Builder builder = new AlertDialog.Builder(this)
                    .setTitle("退出登录")
                    .setMessage("你确定要退出登录吗？");
            builder.setPositiveButton("退出登录", (dialog, whith) -> {
                Toast.makeText(this, "你已退出登录", Toast.LENGTH_LONG).show();
                //退出程序
                finish();
                Process.killProcess(Process.myPid());
                System.exit(1);
            });
            builder.setNegativeButton("取消", (dialog, w) -> {
                dialog.dismiss();
            });
            builder.create().show();
        });
    }
}